
package vista.gen;

import java.net.URL;
import java.util.ArrayList;
import javax.swing.JComponent;
import org.hibernate.Session;
import util.HibernateUtil;
import vista.gen.renders.RenderAbstracto;

/**
 * @author Iuga
 */
public class PantallaABMGenerica extends javax.swing.JInternalFrame {

    protected Class clase;
    protected int id = -1;
    private ArrayList<RenderAbstracto> listaRenders;
    
    private Object dataLoaded = null;
    
    private static final String MAPPING_DIR = "/config/db/";
    
    public static final int COMPORTAMIENTO_ALTA         = 0;
    public static final int COMPORTAMIENTO_BAJA         = 1;
    public static final int COMPORTAMIENTO_MODIFICACION = 2;
    public static final int COMPORTAMIENTO_VER          = 3;
    
    private int comportamiento = 0; // por defecto es una ALTA
    
    private PantallaABMGenericaParseHibXml _parser;
    
    /**
     * Creates new form PantallaABMGenerica
     */
    public PantallaABMGenerica(Class clase, int comportamiento) {
        this.comportamiento = comportamiento;
        this.clase = clase;
        this.listaRenders = new ArrayList<RenderAbstracto>();
        initComponents();
        initRender();
        render();
    }
    
    public PantallaABMGenerica(Class clase, int comportamiento, int id) {
        this.comportamiento = comportamiento;
        this.clase = clase;
        this.id = id;
        this.listaRenders = new ArrayList<RenderAbstracto>();
        loadEntity();
        initComponents();
        initRender();
        render();
    }    
        

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        panelRenders = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        panelRenders.setLayout(new javax.swing.BoxLayout(panelRenders, javax.swing.BoxLayout.Y_AXIS));
        jScrollPane1.setViewportView(panelRenders);

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/save_upload.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/block.png"))); // NOI18N
        btnCancelar.setText("Cancelar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
                        .addComponent(btnCancelar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnGuardarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelRenders;
    // End of variables declaration//GEN-END:variables

    private void render() {
        // Seteo el nombre a la ventana
        this.setTitle(getNombreVentana());
        // Renderizo los componentes
        for (int i = 0; i < listaRenders.size(); i++) {
            // Render
            RenderAbstracto render = listaRenders.get(i);
            JComponent cp = render.render(this.comportamiento);
            
            if(this.comportamiento==COMPORTAMIENTO_MODIFICACION 
                    ||this.comportamiento==COMPORTAMIENTO_VER
                    ||this.comportamiento==COMPORTAMIENTO_BAJA)
            {
                render.setData(getDataFromAttribute(render.getAttrName()));
            }
            
            if(cp!=null)
            {
                panelRenders.add(cp);
            }
        }
    }

    private void initRender() {
        URL fileHbmURL = getClass().getResource(MAPPING_DIR+FactoryABM.getHibernateHbm(this.clase));
        this._parser = new PantallaABMGenericaParseHibXml(fileHbmURL);
        this.listaRenders = this._parser.parseEntidad(getNombresCampos());
    }
    
    protected String getNombreVentana()
    {
        switch(this.comportamiento)
        {
            case COMPORTAMIENTO_ALTA: return "Nueva Entidad";
            case COMPORTAMIENTO_BAJA: return "Dat de Baja la Entidad";
            case COMPORTAMIENTO_MODIFICACION: return "Modificar una Entidad";
            case COMPORTAMIENTO_VER: return "Detalles de la Entidad";
        }
        return "";
    }
    
    protected ArrayList<String[]> getNombresCampos()
    {
        return new ArrayList<String[]>();
    }

    private void loadEntity() {
        try
        {
            Session sesion= HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            Object data = sesion.load(this.clase,this.id);
            HibernateUtil.commitTransaction();
            this.dataLoaded = data;
            System.out.println("[DEBUG] DATA LOADED"+data);
        } catch (Exception ex)
        {
            System.out.println("No se pudo abrir la sesion");
            HibernateUtil.rollbackTransaction();
        }
    }
    
    private String getDataFromAttribute(String attr)
    {
        String result = "";
        // Busco el getter a usar
        String f = attr.substring(0,1);
        StringBuilder firtsUpper = new StringBuilder("get");
        firtsUpper.append(f.toUpperCase());
        firtsUpper.append(attr.substring(1,attr.length()));
        String getter = firtsUpper.toString();
        System.out.println("[DEBUG] Getter = "+getter+"();");
        // Ya tengo el getter, lo invoco
        java.lang.reflect.Method method; 
        try 
        {
            method = this.dataLoaded.getClass().getMethod(getter);
            result = (String) String.valueOf(method.invoke(this.dataLoaded));
            System.out.println("[DEBUG] El Getter retorno: "+result);
            
        }catch(Exception e)
        {
            System.err.println("[ERROR] No se pudo invocar el metodo "+getter);
        }
        return result;
    }
}
